﻿using HoverTree.DBTools;
using HoverTree.HoverTreeFrame;
using HoverTree.HoverTreeFrame.HvtImage;
using HoverTree.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;

namespace HoverTree.SQLServerDAL
{
    public class HvtPicture : IDAL.IPicture
    {
        public string Add(PictureInfo picInfo, FileUpload fileUpload)
        {
            return Add(picInfo, fileUpload, new HvtPicConfig());
        }

        public string Add(PictureInfo picInfo, FileUpload fileUpload, HvtPicConfig config)
        {
            string m_return = string.Empty;
            string m_fileExtension;
            m_return = CheckPic(fileUpload, out m_fileExtension);

            if (m_return != string.Empty)
            {
                return m_return;
            }
            picInfo.HvtSuffix = m_fileExtension;

            picInfo = PreparePictureInfo(picInfo);

            string m_sql = "insert into hovertr"
                + "ee_picture(hvtfilename,hvtsuffix,hvtfolder"
                + ",hvttime,hvttitle,hvtnote,hvtisshow,hvtishome,hvtistop,hvtlink,hvtimagesetid)values(" + SQLTools.GetQuotes(picInfo.HvtFilename)
                + "," + SQLTools.GetQuotes(picInfo.HvtSuffix) + "," + SQLTools.GetQuotes(picInfo.HvtFolder)
                + "," + SQLTools.GetQuotes(picInfo.HvtTime.ToString())
                + "," + SQLTools.GetQuotes(picInfo.HvtTitle)
                + "," + SQLTools.GetQuotes(picInfo.HvtNote)
                + "," + Convert.ToInt32(picInfo.HvtIsshow).ToString()
                + "," + Convert.ToInt32(picInfo.HvtIshome).ToString()
                + "," + Convert.ToInt32(picInfo.HvtIsTop).ToString()
                + "," + SQLTools.GetQuotes(picInfo.HvtLink)
                + "," + picInfo.HvtImageSetId.ToString()
                + " )";

            int m_i = KeleyiSQLHelper.ExecuteSql(m_sql);
            if (m_i != 1)
            {
                m_return = "添加记录失败。";
                return m_return;
            }

            string m_saveFolder = Utils.GetMapPath("/") + "hvtimg/" + picInfo.HvtFolder + "/";

            if (!Directory.Exists(m_saveFolder))
                Directory.CreateDirectory(m_saveFolder);

            HoverTreePicture.HvtPicUp(fileUpload, m_saveFolder, picInfo.HvtFilename, picInfo.HvtSuffix,config);

            return string.Empty;
        }

        PictureInfo PreparePictureInfo(PictureInfo pictureInfo)
        {
            DateTime m_now = DateTime.Now;
            if (pictureInfo.HvtTime.Year < 1900)
                pictureInfo.HvtTime = m_now;

            if (pictureInfo.HvtFolder == string.Empty)
                pictureInfo.HvtFolder = m_now.ToString("yyyyMM");

            if (pictureInfo.HvtFilename == string.Empty)
                pictureInfo.HvtFilename = Utils.GetHoverTreeString();

            return pictureInfo;
        }

        private string CheckPic(FileUpload fuPic, out string fileExtension)
        {
            string m_tips = string.Empty;
            fileExtension = string.Empty;
            if (!(fuPic.HasFile))
            {
                m_tips = "请先选择图片";
                return m_tips;
            }
            fileExtension = GetImageFileExtension(fuPic.PostedFile.ContentType);
            if (fileExtension == string.Empty)
            {
                m_tips = fuPic.PostedFile.ContentType + "只能上传图片,请选择图片文件(jpg,gif,bmp,png)";
            }
            else if (fuPic.PostedFile.ContentLength > 1048576)
            {
                m_tips = "文件太大";
            }
            return m_tips;
        }

        string GetImageFileExtension(string contentType)
        {
            switch (contentType)
            {
                case "image/jpeg":
                    return ".jpg";
                case "image/pjpeg":
                    return ".jpg";
                case "image/gif":
                    return ".gif";
                case "image/bmp":
                    return ".bmp";
                case "image/png":
                    return ".png";
                case "image/x-png":
                    return ".png";
                default:
                    return string.Empty;
            }
        }


        public List<PictureInfo> HvtPageQuery(PictureSelect pictureSelect, int sortType, int pageSize, int pageIndex, out int totalCount, out int totalPageCount)
        {

            string m_where = " 1=1 ";
            if (pictureSelect.HvtIsShow == 1)
                m_where = m_where + " and hvtisshow=1 ";
            else if (pictureSelect.HvtIsShow == 0)
                m_where = m_where + " and hvtisshow=0 ";

            if (pictureSelect.HvtIsHome == 1)
                m_where = m_where + " and HvtIsHome=1 ";
            else if (pictureSelect.HvtIsHome == 0)
                m_where = m_where + " and HvtIsHome=0 ";

            string m_orderBy;
            if (pictureSelect.HvtImageSetId > 0)
            {
                //按图集查询图片,封面排在前面
                m_where = m_where + " and hvtimagesetid= " + pictureSelect.HvtImageSetId.ToString();
                m_orderBy = " hvtiscover desc,hvtistop desc, hvtId desc  ";
            }
            else
            {
                //查询全部图片时,封面不做特殊处理
                m_orderBy = " hvtistop desc, hvtId desc  ";
            }

            DataTable m_dt = KeleyiSQLHelper.HvtPageQuery("hove" + "r" + "tree_picture", "*", "hvtid", m_where
                , m_orderBy, sortType, pageSize, pageIndex, 0, out totalCount, out totalPageCount);

            return ConvertToList(m_dt);
        }

        public PictureInfo ConvertDataRowToInfo(DataRow row)
        {
            PictureInfo m_info = new PictureInfo();

            m_info.HvtIsTop = Convert.ToBoolean(row["HvtIsTop"]);
            m_info.HvtLink = row["HvtLink"].ToString();
            m_info.HvtImageSetId = Convert.ToInt32(row["HvtImageSetId"]);
            m_info.HvtTitle = row["hvttitle"].ToString();
            m_info.HvtNote = row["hvtnote"].ToString();
            m_info.HvtFilename = row["hvtfilename"].ToString();
            m_info.HvtId = Convert.ToInt32(row["hvtid"]);
            m_info.HvtTime = Convert.ToDateTime(row["hvtTime"].ToString());
            m_info.HvtIsshow = Convert.ToBoolean(row["hvtisshow"]);
            m_info.HvtIshome = Convert.ToBoolean(row["hvtishome"]);
            m_info.HvtSuffix = row["hvtsuffix"].ToString();
            m_info.HvtFolder = row["hvtfolder"].ToString();

            return m_info;
        }

        List<PictureInfo> ConvertToList(DataTable pictureTable)
        {
            List<PictureInfo> m_pictureList = new List<PictureInfo>();
            if (pictureTable == null)
                return null;
            int m_rows = pictureTable.Rows.Count;
            if (m_rows == 0)
                return m_pictureList;

            for (int i = 0; i < m_rows; i++)
            {
                m_pictureList.Add(ConvertDataRowToInfo(pictureTable.Rows[i]));
            }

            return m_pictureList;
        }


        public PictureInfo Get(PictureSelect select)
        {
            string m_where = "";
            if (select.HvtId > 0)
                m_where = m_where + " hvtid=" + select.HvtId.ToString();
            else if (select.HvtFileName != string.Empty)
            {
                m_where = m_where + " hvtfilename=" + SQLTools.GetQuotes(select.HvtFileName);
            }
            else
                return null;

            if (select.HvtIsShow == 1)
                m_where = m_where + " and hvtisshow=1 ";
            else if (select.HvtIsShow == 0)
                m_where = m_where + " and hvtisshow=0 ";

            if (select.HvtIsHome == 1)
                m_where = m_where + " and HvtIsHome=1 ";
            else if (select.HvtIsHome == 0)
                m_where = m_where + " and HvtIsHome=0 ";

            string m_sql = "select  * from hovertree_picture where " + m_where;

            DataRow m_dr = KeleyiSQLHelper.QueryRow(m_sql);

            if (m_dr == null)
                return null;

            PictureInfo m_pictureInfo = new PictureInfo();

            m_pictureInfo = ConvertDataRowToInfo(m_dr);

            return m_pictureInfo;
        }

        public string ReUpload(PictureInfo pictureInfo, FileUpload fileUpload, HvtPicConfig config)
        {
            string m_return = string.Empty;
            string m_fileExtension;
            m_return = CheckPic(fileUpload, out m_fileExtension);

            if (m_return != string.Empty)
            {
                return m_return;
            }

            string m_saveFolder = Utils.GetMapPath("/") + "hvtimg/" + pictureInfo.HvtFolder + "/";

            if (pictureInfo.HvtSuffix != m_fileExtension)
            {
                //删除原图
                string m_formerFile = m_saveFolder + pictureInfo.HvtFilename + pictureInfo.HvtSuffix;
                string m_formerListFile = m_saveFolder + pictureInfo.HvtFilename + "_l" + pictureInfo.HvtSuffix;
                if (File.Exists(m_formerFile))
                    File.Delete(m_formerFile);
                if (File.Exists(m_formerListFile))
                    File.Delete(m_formerListFile);

                //修改数据库后缀

                string m_sql = "update hovertree_picture set hvtsuffix=" + SQLTools.GetQuotes(m_fileExtension) + " where hvtid=" + pictureInfo.HvtId.ToString();
                int m_i = KeleyiSQLHelper.ExecuteSql(m_sql);
                if (m_i != 1)
                {
                    return "原图已经删除,修改后缀失败";
                }
            }

            pictureInfo.HvtSuffix = m_fileExtension;


            if (!Directory.Exists(m_saveFolder))
                Directory.CreateDirectory(m_saveFolder);

            string m_saveFullName = m_saveFolder + pictureInfo.HvtFilename + pictureInfo.HvtSuffix;

            HoverTreePicture.HvtPicUp(fileUpload, m_saveFolder, pictureInfo.HvtFilename, pictureInfo.HvtSuffix,config);

            return string.Empty;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="pictureInfo">原图信息</param>
        /// <param name="fileUpload">新图信息</param>
        /// <returns></returns>
        public string ReUpload(PictureInfo pictureInfo, FileUpload fileUpload)
        {
            return ReUpload(pictureInfo, fileUpload, new HvtPicConfig());
        }


        public string AlterInfo(PictureInfo pictureInfo)
        {
            string m_where = "";
            //如果图片不可见，即不能对封面设置
            if (!pictureInfo.HvtIsshow)
                m_where = " and hvtiscover=0";

            string m_sql = "update hover" + "tree_picture set "
                + "hvttitle=" + SQLTools.GetQuotes(pictureInfo.HvtTitle)
                + ",hvtnote=" + SQLTools.GetQuotes(pictureInfo.HvtNote)
                + ",hvtisshow=" + Convert.ToInt32(pictureInfo.HvtIsshow).ToString()
                + ",hvtishome=" + Convert.ToInt32(pictureInfo.HvtIshome).ToString()
                + ",hvtistop=" + Convert.ToInt32(pictureInfo.HvtIsTop).ToString()
                + ",hvtlink=" + SQLTools.GetQuotes(pictureInfo.HvtLink)
                + " where hvtid=" + pictureInfo.HvtId.ToString()
                + m_where
                ;

            int m_i = KeleyiSQLHelper.ExecuteSql(m_sql);
            if (m_i == 1)
                return string.Empty;
            else
                return "修改失败";

        }

        /// <summary>
        /// 获取相同图集中的上一张公开图片
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public PictureInfo GetLastPublic(PictureInfo info)
        {
            if (info == null)
                return null;
            return GetBesidePublic(info.HvtImageSetId, info.HvtId, false);
        }

        /// <summary>
        /// 获取相同图集中的下一张公开图片
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public PictureInfo GetNextPublic(PictureInfo info)
        {
            if (info == null)
                return null;
            return GetBesidePublic(info.HvtImageSetId, info.HvtId, true);

        }

        public PictureInfo GetBesidePublic(int imageSetId, int hvtID, bool hvtLastOrNext)
        {
            if (hvtID < 1 || imageSetId < 1)
                return null;

            IDataParameter[] m_parameters = new SqlParameter[3];

            m_parameters[0] = new SqlParameter("@hvtimagesetid", SqlDbType.Int);
            m_parameters[1] = new SqlParameter("@hvtID", SqlDbType.Int);
            m_parameters[2] = new SqlParameter("@hvtLastOrNext", SqlDbType.Int);

            m_parameters[0].Value = imageSetId;
            m_parameters[1].Value = hvtID;
            m_parameters[2].Value = hvtLastOrNext;

            DataRow m_dr;
            m_dr = KeleyiSQLHelper.RunProcedureDataRow("Sp_HoverTree_Picture_GetBeside", m_parameters);

            if (m_dr == null)
                return null;

            return ConvertDataRowToInfo(m_dr);
        }


        public string SetCover(PictureSelect select)
        {
            if (select.HvtId < 1)
                return "不存在图片.";
            select.HvtIsShow = 1;

            PictureInfo m_info = new PictureInfo();
            m_info = Get(select);

            if (m_info == null)
                return "图片不存在或者不公开.";

            if (!m_info.HvtIsshow)
                return "图片不公开，无法设置为封面。";

            IDataParameter[] m_parameters = new SqlParameter[3];

            m_parameters[0] = new SqlParameter("@hvtID", SqlDbType.NVarChar, 20);
            m_parameters[1] = new SqlParameter("@hvtImageSetId", SqlDbType.NVarChar, 50);
            m_parameters[2] = new SqlParameter("@hvtPictrueUrl", SqlDbType.NVarChar, 200);

            m_parameters[0].Value = m_info.HvtId;
            m_parameters[1].Value = m_info.HvtImageSetId;
            m_parameters[2].Value = m_info.HvtSrc;

            int m_returnCount;

            //执行结果等于1表示成功
            m_returnCount = KeleyiSQLHelper.RunProcedureWithReturn("Sp_HoverTree_Picture_SetCover", m_parameters);

            if (m_returnCount == 1)
                return "";
            else
                return "设置失败 ";

        }

        /// <summary>
        /// 作为封面列表
        /// </summary>
        /// <param name="pictureSelect"></param>
        /// <param name="sortType"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="totalCount"></param>
        /// <param name="totalPageCount"></param>
        /// <returns></returns>
        public List<PictureInfo> GetListWithImageSetTitle(PictureSelect pictureSelect, int sortType, int pageSize, int pageIndex, out int totalCount, out int totalPageCount)
        {
            string m_where = " 1=1 ";
            if (pictureSelect.HvtIsShow == 1)
                m_where = m_where + " and hvtisshow=1 ";
            else if (pictureSelect.HvtIsShow == 0)
                m_where = m_where + " and hvtisshow=0 ";

            if (pictureSelect.HvtIsHome == 1)
                m_where = m_where + " and HvtIsHome=1 ";
            else if (pictureSelect.HvtIsHome == 0)
                m_where = m_where + " and HvtIsHome=0 ";

            if (pictureSelect.HvtImageSetId > 0)
                m_where = m_where + " and hvtimagesetid= " + pictureSelect.HvtImageSetId.ToString();

            DataTable m_dt = KeleyiSQLHelper.HvtPageQuery("hvt_v_PictureCoverWithImageSetTitle", "*", "hvtid", m_where
                , "  hvtistop desc, hvtid desc ", sortType, pageSize, pageIndex, 0, out totalCount, out totalPageCount);

            return ConvertToList(m_dt);
        }

        public List<PictureInfo> GetAllPublic()
        {
            return GetAllPublic(-1);
        }

        public List<PictureInfo> GetAllPublic(PictureInfo select)
        {
            string m_where = "  hvtisshow=1 ";

            if (select.HvtImageSetId > 0)
                m_where = m_where + " and HvtImageSetId=" + select.HvtImageSetId.ToString();

            string m_sql = "select  * from hovertree_picture where " + m_where + " order by hvtid desc";

            DataTable m_dt = KeleyiSQLHelper.QueryTable(m_sql);

            return ConvertToList(m_dt);
        }

        public List<PictureInfo> GetAllPublic(int imageSetID)
        {
            PictureInfo m_select = new PictureInfo();
            m_select.HvtImageSetId = imageSetID;
            return GetAllPublic(m_select);
        } 
    }
}